package me.zhyx.music.utils;


import me.zhyx.music.model.Proxy_ip;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class PoiUtil {
    public static List<Proxy_ip> poiToObject(String fileName) throws IOException {
        InputStream is = new FileInputStream(new File(fileName));
        Workbook hssfWorkbook = null;
        if (fileName.endsWith("xlsx")) {
            hssfWorkbook = new XSSFWorkbook(is);//Excel 2007
        } else if (fileName.endsWith("xls")) {
            hssfWorkbook = new HSSFWorkbook(is);//Excel 2003

        }
        Proxy_ip proxyIp ;
        List<Proxy_ip> list = new ArrayList<>();
        // 循环工作表Sheet
        for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
            Sheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            if (hssfSheet == null) {
                continue;
            }
            // 循环行Row
            for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                Row row = hssfSheet.getRow(rowNum);
                if (row != null) {
                    proxyIp = new Proxy_ip();
                    Cell ip = row.getCell(0);
                    Cell port = row.getCell(1);
                    Cell address = row.getCell(2);
                    Cell is_anonymous = row.getCell(3);
                    Cell type = row.getCell(4);
                    proxyIp.setIp(ip.getStringCellValue());
                    proxyIp.setPort((int) (port.getNumericCellValue()));
                    proxyIp.setIs_anonymous(is_anonymous.getStringCellValue());
                    proxyIp.setAddress(address.getStringCellValue());
                    proxyIp.setType(type.getStringCellValue());
                    list.add(proxyIp);
                }
            }

        }
        return list;
    }


}
